//
//  NBStatusViewModel.swift
//  NBSinaWeibo
//
//  Created by ac on 16/5/25.
//  Copyright © 2016年 ac. All rights reserved.
//

import UIKit

class NBStatusViewModel: NSObject {
    var status:NBStatus?;
    
    var headURL:NSURL?
    var verifiedImage: UIImage?
    var mbrankImage: UIImage?
    var time: String? {
        return NSDate.sinaDate(status?.created_at ?? "")?.fullDescription()
    }
    var source: String?
    
    var repostsText: String?
    
    var commentsText: String?
    
    var attitudesText: String?


    
    init(status:NBStatus) {
        super.init()
        self.status = status
        
        headURL = NSURL(string: status.user!.profile_image_url ?? "")
        
        handleVerifiedImage()
        handleMbrankImage()
        handleSource()
        
        commentsText = dealToolBarText(status.comments_count, defaultText: "评论")
        repostsText = dealToolBarText(status.reposts_count, defaultText: "转发")
        attitudesText = dealToolBarText(status.attitudes_count, defaultText: "赞")

    }
    
    //在这个方法计算底部工具条显示的文字
    //如果没有评论或者转发或者赞  就显示默认文字
    //- 有相关的数据 就显示对应的数据,但是如果超过一万条 就应该显示多少万条
    func dealToolBarText(count: Int,defaultText: String) -> String {
        
        //let count = 11000
        if count <= 0 {
            return defaultText
        }
        //大于一万
        if count >= 10000 {
            return "\(Double(count / 1000) / 10)万"
        }
        return "\(count)"
    }

    
    private func handleSource(){
        //<a href=\"http://app.weibo.com/t/feed/1tqBja\" rel=\"nofollow\">360安全浏览器</a>
        let startFlag = "\">"
        let endFlag = "</a>"
        let str = status?.source ?? ""
        let startRange = str.rangeOfString(startFlag)
        let endRange = str.rangeOfString(endFlag)
        if let start = startRange, end = endRange {
            let range = start.endIndex..<end.startIndex
            source = str.substringWithRange(range)
        }
        //不满足截取条件 就不赋值

    }
    
    
    private func handleVerifiedImage(){
        if status?.user?.verified == 1 {
            verifiedImage = UIImage(named: "avatar_vip")
        }
    }
    
    private func handleMbrankImage(){
        if status?.user?.mbrank > 0 && status?.user?.mbrank < 7 {
            // 1 ~ 6
            //转译会自动加上 optional
            let image = UIImage(named: "common_icon_membership_level\(status?.user?.mbrank ?? 0)")
            mbrankImage = image
        }
    }
    
    
    
    
}
